﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows.Data;
using Betfair.Api;
using Betfair.Api.Types;
using Bull.Core;

namespace Bull.Plugins.Market.ViewModels {
    public sealed class InPlayViewModel : ViewModelBase {
        public ICollectionView EventTypes { get; private set; }
        public MarketBookViewModel MarketBook { get; private set; }

        private readonly IList<EventTypeViewModel> _eventTypes;
 
        public InPlayViewModel()
        {
            _eventTypes = new List<EventTypeViewModel>();
            EventTypes = CollectionViewSource.GetDefaultView(_eventTypes);
            EventTypes.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));

            GetEventTypes()
                .ObserveOn(IoC.Container.Scheduler)
                .Subscribe(eventType =>
                {
                    _eventTypes.Add(eventType);
                    EventTypes.Refresh();
                });

            Mediator.Instance.Register("MarketBooks", obj =>
            {
                var message = (KeyValuePair<MarketCatalogue, Response<IList<MarketBook>>>)obj;
                MarketBook = new MarketBookViewModel(message.Key, message.Value.Result.FirstOrDefault());
                OnPropertyChanged("MarketBook");
            });
        }

        public IObservable<EventTypeViewModel> GetEventTypes()
        {
            return Observable.Create<EventTypeViewModel>(async subject =>
            {
                var eventTypes = await IoC.Container.BetfairProxy.GetEventTypes(
                    IdGenerator.Instance.GetId(),
                    new Params()
                    .SetFilter(new Filter()));
                var tasks = new List<Task>();
                if(eventTypes.ResponseType == ResponseType.OK) {
                    Parallel.ForEach(eventTypes.Result, eventType => tasks.Add(IoC.Container.BetfairProxy.GetEvents(IdGenerator.Instance.GetId(),
                        new Params().SetFilter(new Filter().SetEventTypeId(eventType.Id).SetInPlayOnly(true)))
                        .ContinueWith(eventTask => {
                            var events = eventTask.Result;
                            if(events.ResponseType == ResponseType.OK && events.Result.Count > 0) {
                                subject.OnNext(new EventTypeViewModel(eventType, events.Result));
                            }
                        })));
                }
                return Disposable.Empty;
            });
        }
    }
}
